import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8"); //让缓存区用utf-8存储
            response.setContentType("text/html;charset=utf-8"); //告诉浏览器是一个html类型文件,要用utf8解码
            Map<String, String[]> map = request.getParameterMap();
            webStudent webStudent = new webStudent();
            BeanUtils.populate(webStudent, map);
            BufferedWriter bw = new BufferedWriter(new FileWriter("E:/a.txt", true));
            bw.write(webStudent.getName() + "," + webStudent.getAge() + "," + webStudent.getScore());
            bw.newLine();
            bw.close();

            PrintWriter out = response.getWriter();
            out.println("添加成功,将在两秒后跳转首页");
            response.setHeader("Refresh","2;url="+request.getContextPath()+"/index.html");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
